 function  [fs,bal,resids,prj]=fac_baing(xmat,nk); 
% Computation of the static eigenvalues and eigenvectors from  
% 
% Bai and Ng (2002), "Determining the Number 
% of Factors in Approximate Factor Models", Econometrica
%
% Use baing.m for model selection 
%
% Input
% xmat [TxN] matrix of data 
%
% Output 
% fs  [Txn]  vector of factors (from smallest to most important)
% bal [nxn] vector of loadings 
% Last Modified 3/5/03
% Corrected Variance Scaling for the PCP criterion
% Notes: starts from largest method and works backwards 
%        indicator of model chosen assumed start at 1
% -------------------------------------
% Storage Matrix for the Loss Functions 
% -------------------------------------
% --------------------------------------
[T,N]=size(xmat); 
if nargin < 2 
    ind=N:-1:1; 
else
    if nk > N 
        error('Maximum number of principal components is N')
    end
    ind=N:-1:(N-nk+1);
end
sigxx=xmat'*xmat; % NxN
% Computes normalized eigenvalues and eigenvectors 
% Corresponds to the normalization lambda'*lambda/N=I 
[bal,eigval]=eig(sigxx); 
bal=bal(:,ind)*sqrt(N);  % sqrt(N) times largess eigenvectors
%bal=bal*sqrt(N); 
fs=xmat*bal/N;
% Re-scaled factors 
% fs=fs*((fs'*fs/T)^0.5);
% projections 
prj=fs*bal'; 
resids=xmat-prj; 